<template>
    <div class="todos">
        <header>
            <input type="text" placeholder="亲输入待办事项" autofocus @keyup.enter="addTodo">
        </header>

        <div class="con">
            <input type="checkbox" :checked="allChecked"
                @change="toggleAll(!allChecked)"
            >全选
            <h2>待办事项列表：</h2>
            <ul>
                <todo-item v-for="(todo,index) in filterTodos" :key="index" :todo="todo"></todo-item>
            </ul>
        </div>

        <footer class="footer">
            还有{{remaining}}项为完成

            <div>
                <span style="padding:0 10px;" v-for="(item,key,ind) in filters" 
                :key="ind"
                @click="visibility = key"
                >{{key}}</span>
            </div>
        </footer>

    </div>
</template>
<script>
import todoItem from '../components/todoItem'
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'

let filters = {
    'all':todos => todos,
    'active':todos => todos.filter(item => !item.done),
    'completed':todos => todos.filter(item => item.done)
};
export default {
    data(){
        return {
            visibility:'all',
            filters
        }
    },
    components:{
       todoItem
    },
    computed:{
        todos(){
            return this.$store.state.todos
        },
        allChecked(){
            return this.todos.length && this.todos.every(item => item.done)
        },
        remaining(){
            return this.todos.filter(item => !item.done).length
        },
        filterTodos(){
            return filters[this.visibility](this.todos)
        }
    },
    methods:{
        ...mapActions([
            'toggleAll'
        ]),
        addTodo(e){
            let val = e.target.value.trim();
            this.$store.dispatch('addTodo',val);
            e.target.value='';
        }
    }
}
</script>
